﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
using System.Text;

namespace Universe.WinForms
{
    public class TransparentColorPath
    {
        Image _Image;
        const PixelFormat format = PixelFormat.Format32bppArgb;


        public TransparentColorPath(Image image)
        {
            _Image = image;
        }

        [StructLayout(LayoutKind.Sequential)]
        struct PixelData
        {
            public byte B;
            public byte G;
            public byte R;
            public byte A;

            public PixelData(byte a, byte r, byte g, byte b)
            {
                B = b;
                G = g;
                R = r;
                A = a;
            }
        }

        unsafe static PixelData GetPixelData(Point point, BitmapData data)
        {
            IntPtr pointer = (IntPtr)((int)data.Scan0 + (point.Y * data.Stride) + point.X * sizeof(PixelData));
            PixelData* p = (PixelData*)pointer;
            PixelData ret = new PixelData(p->A, p->R, p->G, p->B);
            return ret;
        }

        static readonly Size OnePixelSize = new Size(1, 1);


        public GraphicsPath GraphicsPath
        {
            get
            {
                GraphicsPath ret = new GraphicsPath();

                Size size = new Size(_Image.Width, _Image.Height);
                using (Bitmap bmp = new Bitmap(size.Width, size.Height, PixelFormat.Format32bppPArgb))
                {
                    using (Graphics g = Graphics.FromImage(bmp))
                    {
                        g.DrawImage(_Image, 0, 0, size.Width, size.Height);
                    }

                    BitmapData data =
                        bmp.LockBits(
                            new Rectangle(0, 0, size.Width, size.Height),
                            ImageLockMode.ReadOnly,
                            PixelFormat.Format32bppPArgb);

                    for (int y = 0; y < size.Height; y++)
                        for (int x = 0; x < size.Width; x++)
                        {
                            Point point = new Point(x, y);
                            PixelData pix = GetPixelData(point, data);
                            if (pix.A < 128)
                                ret.AddRectangle(new Rectangle(point, OnePixelSize));
                        }

                        bmp.UnlockBits(data);
                }

                return ret;
            }
        }

    }
}
